<template>
  <div style="min-height: 500px">
    <div class="flex pb-2 mt-[-34px] h-[36px]">
      <div class="flex-1"></div>
      <template v-if="handleType != 'view'">
        <el-button
          v-if="formData.goods_sku.length > 1"
          @click="handleCopySKU"
          :disabled="disabled"
          >复制SKU供应商信息</el-button
        >
        <el-button class="" :disabled="disabled" @click="addSupplier('binding')"
          ><svg-icon icon-class="add" />绑定供应商</el-button
        >
        <VButton
          auth="/goods/task/product/add-supplier"
          class=""
          :disabled="disabled"
          @click="addSupplier('add')"
          ><svg-icon icon-class="add" />新增并绑定供应商</VButton
        >
      </template>
    </div>
    <div class="my-collapse">
      <template v-for="(row, index) in tableData" :key="row.id">
        <div
          v-if="row.delete != 1"
          :name="row.id"
          :class="activeNames.includes(index) ? 'atv' : ''"
          class="collapse-item"
        >
          <div class="flex w-[100%] title">
            <div
              class="left-box flex items-center justify-center"
              style="flex-direction: column"
            >
              <div>
                <!-- <template v-if="handleType == 'view'">
                  {{ row.is_default_supplier == 1 ? "默认" : "--" }}
                </template> -->
                <template v-if="handleType != 'view'">
                  <el-radio
                    v-model="row.is_default_supplier"
                    :label="1"
                    name="1"
                    @click.prevent="radioChange(row, index)"
                    :disabled="disabled"
                    >设为默认</el-radio
                  >
                </template>
              </div>
              <div v-if="!disabled">
                <el-button type="primary" link @click="copyRow(row, index)"
                  >复制</el-button
                >
                <el-button type="primary" link @click="editRow(row, index)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  link
                  @click="deleteRow(index)"
                  v-if="info.dev_status != 4"
                  >删除</el-button
                >
              </div>

              <el-button
                v-if="handleType == 'view' || disabled"
                type="primary"
                link
                @click="viewRow(row, index)"
                >详情查看</el-button
              >

              <div v-if="row.is_default_supplier == 1 && info.sku && !disabled">
                <VButton
                  auth="/goods/task/product/relevance"
                  type="primary"
                  link
                  @click="relevanceRow(row)"
                  >关联1688
                </VButton>
              </div>

              <div
                class="flex items-center mt-[2px] cursor-pointer"
                @click="onCollapse(index)"
              >
                详情展开
                <ArrowUp v-if="activeNames.includes(index)" /><ArrowDown v-else />
              </div>
            </div>
            <div class="right-box flex-1">
              <div>
                <dataAuthority
                  auth="supplier_name"
                  :value="row.supplier_name"
                  :default_value="row.supplier_code"
                ></dataAuthority>
                <span class="tag" v-if="row.is_default_supplier == 1">默认</span>
              </div>
              <div class="grid grid-cols-6 gap-y-2 mb-[4px]">
                <VText title="SKU" :value="custom_sku" line="1" />
                <template v-for="item in supplierColumn" :key="item.key">
                  <div v-if="purchase_key.includes(item.key)">
                    {{ item.label }}:<dataAuthority
                      :auth="item.key"
                      :value="row[item.key]"
                    ></dataAuthority>
                  </div>
                  <VText
                    :title="item.label"
                    :value="item.option ? item.option[row[item.key]] : row[item.key]"
                    line="1"
                    v-else
                  />
                </template>
              </div>
              <template v-if="is_gathering_link">
                <VText
                  title="采购链接"
                  :value="row.purchase_link"
                  line="1"
                  type="link"
                  @click="openLink(row.purchase_link)"
                />
              </template>
              <template v-else>
                采购链接: {{ row.purchase_link ? "**" : "--" }}
              </template>
            </div>
          </div>

          <transition name="el-zoom-in-top">
            <div class="body" v-if="activeNames.includes(index)">
              <!-- 报关信息 -->
              <CustomInfo
                :supplier="tableData"
                :skuIndex="skuIndex"
                :info="{
                  ...info,
                  is_dangerous: info.is_dangerous,
                  supplier_name: row.supplier_name,
                  is_refund_tax: row.is_refund_tax,
                }"
                @editRow="editRow(row, index, 3)"
              ></CustomInfo>
              <!-- 欧英代产品资料 -->

              <ouyingdai
                :supplier="tableData"
                :index="index"
                @editRow="editRow(row, index, 4)"
              />
              <!-- 产品标识及加工说明 -->
              <productMarking
                :supplier="tableData"
                :index="index"
                @editRow="editRow(row, index, 5)"
              />
            </div>
          </transition>
        </div>
      </template>
    </div>
  </div>
  <SupplierForm
    ref="SupplierFormRef"
    :list="tableData"
    :info="info"
    @SupplierList="supplierList"
    @queryDetail="queryDetail"
  >
  </SupplierForm>
  <Relevance ref="relevanceRef" />
</template>

<script setup name="Sample">
import { computed } from "vue";
import SupplierForm from "./components/SupplierForm.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import Relevance from "@/components/Supplier/Relevance.vue";
import CustomInfo from "./components/CustomInfo";
import ouyingdai from "./components/ouyingdai";
import productMarking from "./components/productMarking";
import { changeOrderExist } from "@/api/index.js";
import { changeOrderSupplier, getCategory } from "../api.js";
import { change_order_category, oversea_location_category } from "@/utils/data.js";
import { fieldPermissionBoolen } from "@/utils/permission.js";

let handleType = reactive(inject("handleType"));
let formData = reactive(inject("form"));

const emit = defineEmits(["update:modelValue", "copySKU", "queryDetail"]);

const activeNames = ref([]);
const onCollapse = (id) => {
  if (activeNames.value.includes(id)) {
    activeNames.value = activeNames.value.filter((v) => v != id);
  } else {
    activeNames.value.push(id);
  }
};

const SupplierFormRef = ref();
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  info: {
    type: Object,
    default: () => {
      return "";
    },
  },
  sku: {
    type: String,
    default: () => {
      return "";
    },
  },
  skuIndex: {
    type: Number,
    default: 0,
  },
});

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/general-info"))
  );
});

const is_gathering_link = computed({
  get() {
    return fieldPermissionBoolen("gathering_link");
  },
  set(val) {},
});

const { info, skuIndex } = toRefs(props);
onMounted(() => {
  setTimeout(() => {
    activeNames.value = [tableData.value?.findIndex((v) => v.is_default_supplier == 1)];
  }, 500);
});
const tableData = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit("update:modelValue", val);
  },
});
const custom_sku = computed({
  get: () => {
    return info.value.sku || info.value.custom_sku;
  },
});

const radioChange = async (row, rowIndex) => {
  if (disabled.value) return;
  const find_supplier = tableData.value.find((i) => i.is_default_supplier);

  const is_change_order_category = change_order_category.includes(
    info.value.spu_category[0]
  );
  const is_oversea_location_category = oversea_location_category.includes(
    info.value.spu_category[0]
  );

  if (
    info.value.sku_id &&
    info.value.dev_status >= 4 &&
    info.value.dev_status != 5 &&
    is_change_order_category &&
    find_supplier != undefined &&
    !info.value.is_combination
  ) {
    try {
      const res = await changeOrderExist({
        sku_id: info.value.sku_id,
      });
      if (res.data.exist) {
        ElMessageBox.confirm(
          "<商品资料变更单>存在待审核的数据，请审核通过后再进行调整。",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(async () => {});
      } else if (is_change_order_category) {
        ElMessageBox.confirm(
          "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(async () => {
          const row_supplier = Object.assign({}, row);
          const default_supplier = Object.assign({}, find_supplier);
          default_supplier.is_default_supplier = 0;
          row_supplier.is_default_supplier = 1;
          const res = await changeOrderSupplier({
            sku_id: info.value.sku_id,
            goods_sku_supplier: [default_supplier, row_supplier],
          });
          ElMessage.success("生成变更单成功");
        });
      } else {
        tableData.value.forEach((item, index) => {
          if (index == rowIndex) {
            item.is_default_supplier = 1;
            change_supplier_purchase(item);
          } else {
            item.is_default_supplier = 0;
          }
        });
      }
    } catch (e) {
      throw Error(e);
    }
  } else {
    if (disabled.value) return;
    tableData.value.forEach((item, index) => {
      if (index == rowIndex) {
        item.is_default_supplier = 1;
        change_supplier_purchase(item);
      } else {
        item.is_default_supplier = 0;
      }
    });
  }
};

const rowIndex = ref(0);
const editRow = (row, index, active) => {
  nextTick(() => {
    rowIndex.value = index;
    row.custom_sku = custom_sku.value;
    SupplierFormRef.value.open(row, "edit", row.sku || row.custom_sku, active);
  });
};

const copyRow = (row, index) => {
  nextTick(() => {
    rowIndex.value = null;
    const item = deepCopyWithPreserveId(row, { goods_sku_identification_processing: [] });
    SupplierFormRef.value.open(item, "copy");
  });
};

const viewRow = (row) => {
  nextTick(() => {
    SupplierFormRef.value.open(row, "view");
  });
};

const deepCopyWithPreserveId = (source, target) => {
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (
        key === "id" ||
        key === "create_time" ||
        key === "create_user" ||
        key === "create_user_text"
      ) {
        // 保留第二个对象内嵌套结构的 id 属性不变
        continue;
      } else if (Array.isArray(source[key])) {
        target[key] = source[key].map((item, index) => {
          if (typeof item === "object" && item !== null) {
            return deepCopyWithPreserveId(item, target[key]?.[index] || {});
          } else {
            return item;
          }
        });
      } else if (typeof source[key] === "object" && source[key] !== null) {
        target[key] = deepCopyWithPreserveId(source[key], target[key] || {});
      } else {
        target[key] = source[key];
      }
    }
  }
  return target;
};

const addSupplier = (type) => {
  nextTick(() => {
    rowIndex.value = null;
    SupplierFormRef.value.open(null, type, custom_sku.value);
  });
};

const supplierList = (row) => {
  nextTick(() => {
    if (rowIndex.value == null) {
      if (row.is_default_supplier) {
        tableData.value.forEach((i) => {
          i.is_default_supplier = 0;
        });
      }
      tableData.value.push(row);
    } else {
      tableData.value.splice(rowIndex.value, 1, row);
    }
    change_supplier_purchase(row);
  });
};

const deleteRow = (index) => {
  ElMessageBox.confirm("确认删除当前供应商信息?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (
      handleType.value == "add" ||
      handleType.value == "copy" ||
      handleType.value == "createSKU"
    ) {
      tableData.value.splice(index, 1);
      if (tableData.value.length) {
        tableData.value[0].is_default_supplier = 1;
      }
    } else {
      if (tableData.value[index].is_default_supplier) {
        if (index == 0 && tableData.value.length > 1) {
          tableData.value[1].is_default_supplier = 1;
        } else {
          tableData.value[0].is_default_supplier = 1;
        }
      }
      tableData.value[index].delete = 1;
    }
  });
};

const handleCopySKU = () => {
  emit("copySKU", "supplier");
};
const validate = () => {
  let falge = tableData.value?.length ? true : false;
  if (!falge) {
    ElMessage.warning("请至少添加一条供应商信息!");
  }
  return falge;
};
defineExpose({ validate });

const relevanceRef = ref();
// 关联1688
const relevanceRow = (row) => {
  relevanceRef.value.open({ ...row, sku: info.value.sku });
};

const supplierColumn = [
  { label: "采购未税价", key: "purchase_untaxed_price" },
  { label: "采购含税价", key: "unit_price_tax" },
  { label: "采购未税报价", key: "unit_price" },
  { label: "发票税点", key: "invoice_tax_rate" },
  { label: "供应商税点", key: "tax_rate" },
  { label: "供应商报价币种", key: "currency" },
  { label: "起批量", key: "min_order_quantity" },
  { label: "最小出货量", key: "min_shipment_quantity" },
  { label: "是否退税", key: "is_refund_tax", option: { 2: "退税", 3: "不退税" } },
  { label: "采购天数", key: "purchase_days" },
  { label: "备料后采购天数", key: "prepare_purchase_day" },
  { label: "供应商状态", key: "status_text" },
  { label: "供应商审核状态", key: "audit_status_name" },
  { label: "供应商类型", key: "purchase_type_name" },
  { label: "供应商负责人", key: "supplier_manage_text" },
];

const purchase_key = ["purchase_untaxed_price", "unit_price_tax", "unit_price"];

const change_supplier_purchase = async (item) => {
  try {
    const res = await getCategory({
      category_ids: info.value.spu_category,
    });
    if (res.data.length) {
      const findItem = [...res.data].reverse().find((i) => i.purchaser_type);
      if (findItem == undefined) return;
      if (findItem.purchaser_type == 1 && item.fba_purchase_id) {
        formData.value.goods_sku[skuIndex.value].purchaser_id = item.fba_purchase_id;
      } else if (findItem.purchaser_type == 2 && item.oversea_purchase_id) {
        formData.value.goods_sku[skuIndex.value].purchaser_id = item.oversea_purchase_id;
      }
    }
  } catch (e) {
    throw Error(e);
  }
};

// 获取详情
const queryDetail = () => {
  emit("queryDetail");
};
</script>

<style lang="scss">
.hidden-row {
  display: none;
}
</style>

<style lang="scss" scoped>
:deep(.my-collapse) {
  font-size: 14px;
  margin-top: -8px;
  svg {
    width: 14px;
    height: 14px;
  }
  .collapse-item {
    margin-top: 8px;
    &.atv {
      border: 1px solid #fcd689;
      .title {
        border: none;
        border-bottom: 1px solid #e6e7e9;
      }
    }
    &:hover {
      .title {
        .right-box {
          background: var(--supplier-item-bg-hover-color) !important;
        }
      }
    }
    .title {
      border: 1px solid #e6e7e9;
      .left-box {
        padding: 10px 8px;
        width: 144px;
        svg {
          width: 1rem;
          height: 1rem;
          margin-top: 3px;
          margin-left: 3px;
        }
      }
      .right-box {
        padding: 10px 8px;
        background: var(--supplier-item-bg-color);
        border-left: 1px solid #e6e7e9;
        width: calc(100% - 144px);
        .tag {
          color: #fff;
          font-size: 10px;
          background: #3487ff;
          padding: 2px 4px;
          border-radius: 4px 0px 4px 0px;
        }
      }
    }
    .body {
      padding-left: 24px;
      padding-bottom: 8px;
    }
  }
}

:deep(.card-border) {
  border: 1px solid #e6e7e9;
  border-bottom: none;
  margin-right: 8px;
  margin-top: 8px;
  .supplier-dtl-title {
    display: inline-block;
    position: relative;
    z-index: 2;
    margin: 8px;
    font-size: 14px;
  }
  .el-table__header {
    .cell {
      font-weight: 400;
    }
  }
}
</style>
